﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
//using UFSoft.U8.Framework.LoginContext;
using YonYou.U8.IN.DataAccess;
using YonYou.U8.IN.Model;
using YonYou.U8.IN.Utility;

namespace YonYou.U8.IN.Framework.Repositories
{
    public class MenuRepository
    {
        protected string _ConnectionStr;

        public MenuRepository(string cnnString)
        {
            if (string.IsNullOrEmpty(cnnString))
            {
                throw new ArgumentNullException("cnnString");
            }
            _ConnectionStr = cnnString;
        }

        public IList<BizMenu> Query()
        {
            try
            {
                string cmdText = CreateQuerySql();
                using (DbContext dbContext = new DbContext(_ConnectionStr))
                {
                    SqlDataReader sqlDataReader = (SqlDataReader)(object)dbContext.QueryDataReader(cmdText);
                    IList<BizMenu> list = new List<BizMenu>();
                    while (sqlDataReader.Read())
                    {
                        BizMenu bizMenu = new BizMenu
                        {
                            Id = sqlDataReader["cMenuId"].ToString(),
                            AuthId = ((sqlDataReader["cAuthId"] == null) ? string.Empty : sqlDataReader["cAuthId"].ToString()),
                            ParentId = ((sqlDataReader["cSupMenuId"] == null) ? string.Empty : sqlDataReader["cSupMenuId"].ToString()),
                            Name = sqlDataReader["cMenuName"].ToString(),
                            Level = int.Parse(sqlDataReader["iLevel"].ToString()),
                            Order = int.Parse(sqlDataReader["iOrder"].ToString()),
                            IsEndGrade = bool.Parse(sqlDataReader["bEndGrade"].ToString()),
                            ImagePath = ((sqlDataReader["cImage"] == null) ? string.Empty : sqlDataReader["cImage"].ToString()),
                            Class = ((sqlDataReader["cClass"] == null) ? string.Empty : sqlDataReader["cClass"].ToString()),
                            Assembly = ((sqlDataReader["cAssembly"] == null) ? string.Empty : sqlDataReader["cAssembly"].ToString()),
                            Entrypoint = ((sqlDataReader["entrypoint"] == null) ? string.Empty : sqlDataReader["entrypoint"].ToString()),
                            ComponentType = TypeConvertor.ToEnumValue(sqlDataReader["iType"].ToString(), ComponentType.Dll),
                            Reserved = ((sqlDataReader["cReserved"] == null) ? string.Empty : sqlDataReader["cReserved"].ToString())
                        };
                        list.Add(bizMenu);
                    }
                    sqlDataReader.Close();
                    return list;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("[实施导航]-[MenuRepository->QueryRoots()]-[StackTrace:{0}]-[Message:{1}]", ex.StackTrace, ex.Message);
            }
            return new List<BizMenu>();
        }

        private string CreateQuerySql()
        {
            //UserData userData = ViewAdvisor.Instance.Context.UserData;
            string arg = "cMenuId,cSupMenuId,cAuthId,cMenuName ,iLevel,bEndGrade ,iOrder ,cImage";
            string format = "((SELECT {0} FROM c WHERE {1}) ORDER BY iLevel ASC,iOrder ASC";
            string text = " SELECT isnull(cSupAuth_Id,'')  FROM UFSYSTEM..ua_supAuths WITH (NOLOCK) where cAuth_Id in (SELECT cAuth_Id FROM UFSYSTEM..UA_HoldAuth WITH (NOLOCK) WHERE cAcc_Id='002'";
                //+ userData.AccID + "' ";
                //"AND iYear='" + userData.iBeginYear + "' AND cUser_Id IN ('" + userData.UserId + "'" + ((userData.Roles.Length > 0) ? ("," + userData.Roles) : "") + "))";
            string empty = string.Empty;
            //if (!userData.IsAdmin)
            //{
            //    empty = string.Format(format, arg, "(cAuthId is null or cAuthId = '' )");
            //    empty = empty.Replace("ORDER BY iLevel ASC,iOrder ASC", "");
            //    empty = empty + "union all (Select * from UFSystem..IN_Menu where  (cAuthId  in (" + text + "))))";
            //    arg = "C1.cMenuId,C1.cSupMenuId,C1.cAuthId,C1.cMenuName ,C1.iLevel,C1.bEndGrade ,C1.iOrder ,C1.cImage ,C2.cClass,C2.cAssembly,C2.entrypoint,C2.iType,C2.cReserved";
            //    return string.Format("SELECT {0} FROM {1} AS C1 Left JOIN [IN_Idt] AS C2 ON C1.cMenuId=C2.cId ORDER BY C1.iLevel ASC,C1.iOrder ASC", arg, empty);
            //}
            arg = "C1.cMenuId,C1.cSupMenuId,C1.cAuthId,C1.cMenuName ,C1.iLevel,C1.bEndGrade ,C1.iOrder ,C1.cImage ,C2.cClass,C2.cAssembly,C2.entrypoint,C2.iType,C2.cReserved";
            return string.Format("SELECT {0} FROM [IN_Menu] AS C1 Left JOIN [IN_Idt] AS C2 ON C1.cMenuId=C2.cId ORDER BY C1.iLevel ASC,C1.iOrder ASC", arg);
        }

        public IList<BizMenu> QueryRoots()
        {
            try
            {
                string arg = "C1.cMenuId,C1.cSupMenuId,C1.cAuthId,C1.cMenuName,C1.iLevel ,C1.bEndGrade ,C1.iOrder ,C1.cImage ,C2.cClass,C2.cAssembly,C2.entrypoint,C2.iType,C2.cReserved";
                string cmdText = string.Format("SELECT {0} FROM [IN_Menu] AS C1 Left JOIN [IN_Idt] AS C2 ON C1.cMenuId=C2.cId WHERE C1.cSupMenuId is null OR C1.cSupMenuId='' ORDER BY C1.iLevel ASC,C1.iOrder ASC", arg);
                using (DbContext dbContext = new DbContext(_ConnectionStr))
                {
                    SqlDataReader sqlDataReader = (SqlDataReader)(object)dbContext.QueryDataReader(cmdText);
                    IList<BizMenu> list = new List<BizMenu>();
                    while (sqlDataReader.Read())
                    {
                        BizMenu bizMenu = new BizMenu();
                        bizMenu.Id = sqlDataReader["cMenuId"].ToString();
                        bizMenu.AuthId = ((sqlDataReader["cAuthId"] == null) ? string.Empty : sqlDataReader["cAuthId"].ToString());
                        bizMenu.ParentId = ((sqlDataReader["cSupMenuId"] == null) ? string.Empty : sqlDataReader["cSupMenuId"].ToString());
                        bizMenu.Name = sqlDataReader["cMenuName"].ToString();
                        bizMenu.Level = int.Parse(sqlDataReader["iLevel"].ToString());
                        bizMenu.Order = int.Parse(sqlDataReader["iOrder"].ToString());
                        bizMenu.IsEndGrade = bool.Parse(sqlDataReader["bEndGrade"].ToString());
                        bizMenu.ImagePath = ((sqlDataReader["cImage"] == null) ? string.Empty : sqlDataReader["cImage"].ToString());
                        bizMenu.Class = ((sqlDataReader["cClass"] == null) ? string.Empty : sqlDataReader["cClass"].ToString());
                        bizMenu.Assembly = ((sqlDataReader["cAssembly"] == null) ? string.Empty : sqlDataReader["cAssembly"].ToString());
                        bizMenu.Entrypoint = ((sqlDataReader["entrypoint"] == null) ? string.Empty : sqlDataReader["entrypoint"].ToString());
                        bizMenu.ComponentType = TypeConvertor.ToEnumValue<ComponentType>(sqlDataReader["iType"].ToString(), ComponentType.Dll);
                        bizMenu.Reserved = ((sqlDataReader["cReserved"] == null) ? string.Empty : sqlDataReader["cReserved"].ToString());
                        list.Add(bizMenu);
                    }
                    sqlDataReader.Close();
                    return list;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("[实施导航]-[MenuRepository->QueryRoots()]-[StackTrace:{0}]-[Message:{1}]", ex.StackTrace, ex.Message);
            }
            return new List<BizMenu>();
        }

        public IList<BizMenu> QueryByParentId(string parentId)
        {
            try
            {
                string arg = "C1.cMenuId,C1.cSupMenuId,C1.cAuthId,C1.cMenuName,C1.iLevel ,C1.bEndGrade ,C1.iOrder ,C1.cImage ,C2.cClass,C2.cAssembly,C2.entrypoint,C2.iType,C2.cReserved";
                string cmdText = string.Format("SELECT {0} FROM [IN_Menu] AS C1 Left JOIN [IN_Idt] AS C2 ON C1.cMenuId=C2.cId WHERE C1.cSupMenuId='{1}'  ORDER BY C1.iLevel ASC,C1.iOrder ASC", arg, parentId);
                using (DbContext dbContext = new DbContext(_ConnectionStr))
                {
                    SqlDataReader sqlDataReader = (SqlDataReader)(object)dbContext.QueryDataReader(cmdText);
                    IList<BizMenu> list = new List<BizMenu>();
                    while (sqlDataReader.Read())
                    {
                        BizMenu bizMenu = new BizMenu();
                        bizMenu.Id = sqlDataReader["cMenuId"].ToString();
                        bizMenu.AuthId = ((sqlDataReader["cAuthId"] == null) ? string.Empty : sqlDataReader["cAuthId"].ToString());
                        bizMenu.ParentId = ((sqlDataReader["cSupMenuId"] == null) ? string.Empty : sqlDataReader["cSupMenuId"].ToString());
                        bizMenu.Name = sqlDataReader["cMenuName"].ToString();
                        bizMenu.Level = int.Parse(sqlDataReader["iLevel"].ToString());
                        bizMenu.Order = int.Parse(sqlDataReader["iOrder"].ToString());
                        bizMenu.IsEndGrade = bool.Parse(sqlDataReader["bEndGrade"].ToString());
                        bizMenu.ImagePath = ((sqlDataReader["cImage"] == null) ? string.Empty : sqlDataReader["cImage"].ToString());
                        bizMenu.Class = ((sqlDataReader["cClass"] == null) ? string.Empty : sqlDataReader["cClass"].ToString());
                        bizMenu.Assembly = ((sqlDataReader["cAssembly"] == null) ? string.Empty : sqlDataReader["cAssembly"].ToString());
                        bizMenu.Entrypoint = ((sqlDataReader["entrypoint"] == null) ? string.Empty : sqlDataReader["entrypoint"].ToString());
                        bizMenu.ComponentType = TypeConvertor.ToEnumValue<ComponentType>(sqlDataReader["iType"].ToString(), ComponentType.Dll);
                        bizMenu.Reserved = ((sqlDataReader["cReserved"] == null) ? string.Empty : sqlDataReader["cReserved"].ToString());
                        list.Add(bizMenu);
                    }
                    sqlDataReader.Close();
                    return list;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("[实施导航]-[MenuRepository->QueryByParentId()]-[StackTrace:{0}]-[Message:{1}]", ex.StackTrace, ex.Message);
            }
            return new List<BizMenu>();
        }
    }
}
